package com.tom.demo.common.utils;


import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.tom.demo.vo.Seal;
import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
public class PdfSealAdder {
    /**
     * 为pdf文件指定页码中添加一个或者多个电子签章
     * @param inputPdfPath
     * @param outputPdfPath
     * @param pageSeals
     */
    public static void addSealsToPdf(String inputPdfPath, String outputPdfPath, Map<Integer, List<Seal>> pageSeals) {
        try (
                //根据路径读取pdf文件
                PdfReader reader = new PdfReader(inputPdfPath);
                //获取文件最终需要保存的位置的输出流
                FileOutputStream fos = new FileOutputStream(outputPdfPath);
        ) {
            PdfStamper stamper = new PdfStamper(reader, fos);
            int totalPages = reader.getNumberOfPages();

            // 遍历每一页
            for (int pageNum = 1; pageNum <= totalPages; pageNum++) {
                List<Seal> seals = pageSeals.get(pageNum);
                if (seals == null || seals.isEmpty()) {
                    continue; // 该页无签章，跳过
                }
                log.info("正在为第{}页pdf文件添加电子签章",pageNum);
                PdfContentByte content = stamper.getOverContent(pageNum); // 覆盖在内容上方

                for (Seal seal : seals) {
                    try {
                        Image sealImage = Image.getInstance(seal.getImagePath());
                        sealImage.scaleAbsolute(seal.getWidth(), seal.getHeight());
                        sealImage.setAbsolutePosition(seal.getX(), seal.getY());
                        content.addImage(sealImage);
                    } catch (IOException | DocumentException e) {
                        log.error("加载或添加签章失败（第{}页,签章路径是:{} ,异常信息是：{}", pageNum, seal.getImagePath(),e.getMessage(),e);
                        throw new RuntimeException("第"+pageNum+"页pdf添加电子签章失败,异常信息:"+e.getMessage());
                    }
                }
            }
            // 显式关闭以确保写入完成（虽然 try-with-resources 会处理，但 iText 5 有时需要）
            stamper.close();
            log.info("签章已成功添加到 PDF:{} " , outputPdfPath);

        } catch (IOException | DocumentException e) {
            log.error("处理 PDF 时发生错误:{} " , e.getMessage(),e);
            throw new RuntimeException("处理 PDF 时发生错误,异常信息:"+e.getMessage());
        }
    }
}